package com.jintoufs.weixin;

import com.jintoufs.service.weixin.CoreService;
import com.jintoufs.util.weixin.SignUtil;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * Created by yh on 2015/6/16.
 */
@Controller
@Scope("prototype")
@RequestMapping("/com/jintoufs/service/weixin")
public class WeixinAction extends SupportAction {
    @Resource
    private CoreService coreService;
    @Value("${service_secret}")
    private String appsecret;

    @Value("${service_appId}")
    private String appid;

    @ResponseBody
    @RequestMapping(value = "security", method = RequestMethod.GET)
    public void doGet(
            HttpServletRequest request,
            HttpServletResponse response, @RequestParam(value = "signature", required = true) String signature,
            @RequestParam(value = "timestamp", required = true) String timestamp,
            @RequestParam(value = "nonce", required = true) String nonce,
            @RequestParam(value = "echostr", required = true) String echostr) {
        System.out.println("start to get token");
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            PrintWriter out = null;
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.print(echostr);
            out.close();
        } else {
            System.out.println("error");
        }
    }

    @RequestMapping(value = "security", method = RequestMethod.POST)
    public void post(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("UTF-8");
        System.out.println("..........start to processRequest..........");

        // 调用核心业务类接收消息、处理消息
        String respMessage = coreService.processRequest(request);

        // 响应消息
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(respMessage);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            out = null;
        }
    }

    @Bean
    public WxMpService wxMpService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
//        wxMpService.setMaxRetryTimes(100000);

        /** 设置自定义菜单 */
        try {
            MenuConfig menuConfig = new MenuConfig(wxMpService);
            System.out.println("appID:"+appid);
            wxMpService.getMenuService().menuCreate(menuConfig.getMenu());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wxMpService;
    }

    @Bean
    public WxMpConfigStorage wxMpConfigStorage() {
        WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
        configStorage.setAppId(appid);
        configStorage.setSecret(appsecret);
//        configStorage.setToken(token);
//        configStorage.setAesKey(aeskey);
        return configStorage;
    }
}
